package com.baitiaojun.dict.core.utils;

import com.baitiaojun.common.constants.Constants;
import com.baitiaojun.common.utils.object.BeanUtils;
import com.baitiaojun.common.utils.spring.SpringUtils;
import com.baitiaojun.dict.core.models.SysDict;
import com.baitiaojun.redis.core.support.RedisSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 字典工具
 */
public class DictUtils {

    private static final RedisSupport redisSupport = SpringUtils.getBean(RedisSupport.class);

    private static final Long defaultExpire = 1L;

    /**
     * 添加缓存字典
     * @param key
     * @param sysDictList
     */
    public static void setDict(String key, List<SysDict> sysDictList) {
        if (redisSupport != null) {
            redisSupport.addValue(Constants.SYS_DICT_KEY, key, sysDictList, defaultExpire, TimeUnit.DAYS);
        }
    }

    /**
     * 获取缓存字典
     * @param key
     * @return
     */
    public static List<SysDict> getDict(String key) {
        if (redisSupport == null) {
            return new ArrayList<>();
        }
        return BeanUtils.toBeanList(redisSupport.getValue(Constants.SYS_DICT_KEY, key), SysDict.class);
    }

    /**
     * 删除缓存字典
     * @param key
     * @return
     */
    public static Boolean delDict(String key) {
        if (redisSupport == null) {
            return false;
        }
        return redisSupport.delete(Constants.SYS_DICT_KEY, key);
    }

    /**
     * 清空缓存字典
     * @return
     */
    public static Boolean clear() {
        if (redisSupport == null) {
            return false;
        }
        return redisSupport.delete(Constants.SYS_DICT_KEY, redisSupport.keys(Constants.SYS_DICT_KEY));
    }
}
